14. Idling Resource Code Sample - Part 1

Idling Resource Code Sample - Part 1

The Tea shop that I’m building the TeaTime app for will actually have a lot more than the 6 types of tea that we’re currently have in the ArrayList. The owner is quite the tea enthusiast, constantly importing new teas and adding them to her menu.

This means that when users open up TeaTime, it’ll need to download the latest menu images and description.

Hmm sounds suspiciously like the smoothie scenario we just saw in the previous quiz. Not planned at all. I promise :)

However before we dive into implementing IdlingResource, let’s see a simple example of how to set this up.

Basic Idling Resource Example App

The Android Testing team created a Basic Idling Resource app sample.
I recommend opening the code from the link below and exploring the files along with me.

Find Code Here

Here’s what the app looks like when it runs:

Type in EditText field > Click button > Delay message > TextView displays typed message

Type in EditText field > Click button > Delay message > TextView displays typed message

Code Walk-Through

There are 3 java files - SimpleIdlingResource.java, MainActivity.java, and MessageDelayer.java.

SimpleIdlingResource.java

Let’s start with SimpleIdlingResource.java

As the comment on the top of the file states, this is a very simple implementation of the IdlingResource interface:

Because it is an interface, we can see from the Developer doc that we're required to complete the following 3 methods:

These methods are implemented here:

In the code above we also initiate an AtomicBoolean object to control the state of idleness. This class provides us with a boolean variable that can be read and written to automatically. AtomicBooleans are used when multiple threads need to check and change the boolean. This happens to be perfect for our situation.

Remember that if idle is false there are pending operations in the background and any testing operations should be paused.
If idle is true all is clear and testing operations can continue.

Summary

Implementing the IdlingResource interface is straight forward: it requires completing the 3 required methods. We also created an instance of AtomicBoolean in order to control idleness across multiple threads.

Next we'll discuss MainActivity where we will use the IdlingResource.


Learn More About: